package com.xiaomi.myautotest;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.xiaomi.myautotest.entity.CPUFreqEntity;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final ExecutorService executorService = new ThreadPoolExecutor(20, 100, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
    private final static String CPU_4_MAX_FREQ_PATH = "/sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq";
    private final static String CPU_4_CUR_FREQ_PATH = "/sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_cur_freq";
    private final static String CPU_7_MAX_FREQ_PATH = "/sys/devices/system/cpu/cpu7/cpufreq/scaling_max_freq";
    private final static String CPU_7_CUR_FREQ_PATH = "/sys/devices/system/cpu/cpu7/cpufreq/cpuinfo_cur_freq";
    private final static String PHONE_BODY_TEMPERATURE_PATH = "/sys/class/thermal/thermal_message/board_sensor_temp";
    private final static String DECRYPT_PATH = "/data/vendor/thermal/decrypt.txt";
    private final static String CAT_PATH = "/system/bin/cat";
    private volatile boolean flag = false;
    private final static String CMD_FOR_MAX_CPU = "while true;do done&";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startTest = (Button) findViewById(R.id.startTest);
        Button stopTest = (Button) findViewById(R.id.stopTest);
        startTest.setOnClickListener(this);
        stopTest.setOnClickListener(this);
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.startTest:
                startTest();
            case R.id.stopTest:
                executorService.submit(() -> {
                    flag = false;
                });
                break;
            default:
                break;
        }
    }


    /**
     * 开始测试
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void startTest() {
        forMaxCpuRunning();
        executorService.submit(() -> {
            flag = true;
            autoReadInfo();
        });
    }

    /**
     * 获取decrypt.txt日志的信息
     *
     * @return 通过key开头节点
     */
    //TODO 有点小问题目前
    private List<CPUFreqEntity> getDecryptMessage() {
        System.out.println("进来");
        String value = null;
        BufferedReader reader = null;
        try {
            reader = getCMDExecutorReader(CAT_PATH, DECRYPT_PATH);
            String s = null;
            while ((s = reader.readLine()) != null) {
                if ("[SS-CPU4]".equals(s) || "[SS-CPU7]".equals(s)) {
                    int count = 4;
                    StringBuilder str = new StringBuilder();
                    while (count != 0 && (s = reader.readLine()) != null) {
                        count--;
                    }
                    count = 3;
                    while (count != 0 && (s = reader.readLine()) != null) {
                        str.append(s);
                        count--;
                    }
                    Log.d("MyMessage", str.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 读取各个信息
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void autoReadInfo() {
        while (flag) {
            try {
                CompletableFuture<String> getCpu4MaxFreq = CompletableFuture.supplyAsync(() -> getCpuFreqOrTemperature(CPU_4_MAX_FREQ_PATH), executorService);
                CompletableFuture<String> getCpu4CURFreq = CompletableFuture.supplyAsync(() -> getCpuFreqOrTemperature(CPU_4_CUR_FREQ_PATH), executorService);
                CompletableFuture<String> getCpu7MaxFreq = CompletableFuture.supplyAsync(() -> getCpuFreqOrTemperature(CPU_7_MAX_FREQ_PATH), executorService);
                CompletableFuture<String> getCpu7CURFreq = CompletableFuture.supplyAsync(() -> getCpuFreqOrTemperature(CPU_7_CUR_FREQ_PATH), executorService);
                CompletableFuture<String> getCurTemperature = CompletableFuture.supplyAsync(() -> getCpuFreqOrTemperature(PHONE_BODY_TEMPERATURE_PATH), executorService);
                CompletableFuture.allOf(getCpu4CURFreq, getCpu4MaxFreq, getCpu7MaxFreq, getCpu7CURFreq, getCurTemperature);
                String cpu4MaxFreq = getCpu4MaxFreq.get();
                String cpu4CurFreq = getCpu4CURFreq.get();
                String cpu7MaxFreq = getCpu7MaxFreq.get();
                String cup7CURFreq = getCpu7CURFreq.get();
                String bodyTemperature = getCurTemperature.get();
//                TimeUnit.SECONDS.sleep(1L);
                MainActivity.this.runOnUiThread(() -> {
                    TextView curCup4TextView =  findViewById(R.id.curCpu4Freq);
                    TextView maxCup4TextView =  findViewById(R.id.maxCpu4Freq);
                    TextView curCup7TextView =  findViewById(R.id.curCpu7Freq);
                    TextView maxCup7TextView =  findViewById(R.id.maxCpu7Freq);
                    TextView bodyTemperatureTextView = findViewById(R.id.bodyTemperature);
                    curCup4TextView.setText(cpu4MaxFreq);
                    maxCup4TextView.setText(cpu4CurFreq);
                    curCup7TextView.setText(cpu7MaxFreq);
                    maxCup7TextView.setText(cup7CURFreq);
                    bodyTemperatureTextView.setText(bodyTemperature);
                });
                Log.d("MyLog", "壳温: " + bodyTemperature + "  CPU4MAX: " + cpu4MaxFreq + "  CPU4CUR: " + cpu4CurFreq + "  cpu7MaxFreq: " + cpu7MaxFreq + "  cup7CURFreq: " + cup7CURFreq);
            } catch (ExecutionException e) {
                e.printStackTrace();
                break;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 读取某个传感器
     *
     * @return
     */
    private String getCpuFreqOrTemperature(String path) {
        String value = null;
        BufferedReader reader = null;
        try {
            reader = getCMDExecutorReader(CAT_PATH, path);
            String readLine = reader.readLine();
            if (!TextUtils.isEmpty(readLine)) {
                value = readLine;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    /**
     * 获取CMD命令执行的某个reader
     *
     * @param cmd
     * @param path
     * @return
     */
    private BufferedReader getCMDExecutorReader(String cmd, String path) {
        File file = new File(path);
        BufferedReader reader = null;
        if (file.exists()) {
            try {
                ProcessBuilder executor = new ProcessBuilder(cmd, file.getPath());
                Process process = executor.start();
                reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return reader;
    }


    /**
     * 拉满CPU
     */
    private void forMaxCpuRunning() {
        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        Process p = null;
        try {
            p = Runtime.getRuntime().exec("su");
            for (int i = 0; i < 8; i++) {
                outputStream = p.getOutputStream();
                dataOutputStream = new DataOutputStream(outputStream);
                dataOutputStream.writeBytes(CMD_FOR_MAX_CPU);
                dataOutputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}